package com.gl.goods.ui.login.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gl.goods.R;
import com.gl.goods.base.BaseActivity;
import com.gl.goods.base.HXYXConstant;
import com.gl.goods.httpclint.HttpApi;
import com.gl.goods.httpclint.response.JsonResponseHandler;
import com.gl.goods.ui.login.bean.UserInfoBean;
import com.gl.goods.ui.main.activity.MainActivity;
import com.gl.goods.ui.splash.FileUtil;
import com.gl.library.tool.RxSPTool;
import com.gl.library.tool.RxTool;
import com.gl.library.utils.SharedPreferencesUtils;
import com.gl.library.utils.StatusBarUI;
import com.gl.library.utils.StringUtils;
import com.gl.library.widget.edittext.ClearEditText;
import com.gl.library.widget.smartloadview.SmartLoadingView;
import com.google.gson.Gson;
import com.hjq.toast.ToastUtils;
import com.simple.spiderman.SpiderMan;
import com.zj.singclick.SingleClick;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import butterknife.BindView;
import butterknife.OnClick;

/**
 *@description:用户登录Activity
 */
public class LoginActivity extends BaseActivity implements TextWatcher {
    @BindView(R.id.tv_login)
    SmartLoadingView login;
    @BindView(R.id.et_phone)
    ClearEditText et_phone;
    @BindView(R.id.et_password)
    ClearEditText et_password;
    @BindView(R.id.tv_skip)
    TextView mSkipTv;
    @BindView(R.id.iv_close)
    ImageView iv_close;
    @BindView(R.id.rel_finish)
    RelativeLayout rel_finish;
    private String type;
    @Override
    protected int initLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        //测试和主分支merge
        setTitleVisibility(true);
        StatusBarUI.setStatusBarTranslucent(mActivitySelf);
        type = getIntent().getStringExtra("type");

        et_phone.addTextChangedListener(this);
        et_password.addTextChangedListener(this);

//        FileUtil fileUtil = new FileUtil(mActivitySelf);
//        String detail = "";
//        try {
//            detail = fileUtil.read("tvSampleInfo.txt");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        Toast.makeText(getApplicationContext(), detail, Toast.LENGTH_SHORT).show();

        String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        String fileName = "tvSampleInfo.txt";
        File myFile = new File(baseDir + File.separator + fileName);
        try {
            FileInputStream fIn = new FileInputStream(myFile);
            BufferedReader myReader = new BufferedReader(
                    new InputStreamReader(fIn));
            String text = "";
            String aDataRow = "";
            while ((aDataRow = myReader.readLine()) != null) {
                text += aDataRow + "\n";
            }
            Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
        }
        catch (IOException e) {

        }



    }

    @Override
    public void widgetClick(View view) {
        if (StringUtils.equals(type,"splash")){
            mSkipTv.setVisibility(View.VISIBLE);
        }else {
            mSkipTv.setVisibility(View.GONE);
            iv_close.setVisibility(View.VISIBLE);
        }
    }

    @SingleClick(1500)
    @OnClick({R.id.tv_login,R.id.tv_forgot_password,R.id.tv_register,R.id.tv_skip,R.id.rel_finish})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.tv_login:
                hideSoftKeyBoard(mActivitySelf);
                showDialogLoading(R.string.loading);
                login.start();
                String phone = et_phone.getText().toString();
                String pwd = et_password.getText().toString();
                HttpApi.login(phone, pwd, new JsonResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, JSONObject response) {
                        super.onSuccess(statusCode, response);
                        hideDialogLoading();
                        Gson gson = new Gson();
                        UserInfoBean successBean = gson.fromJson(response.toString(), UserInfoBean.class);
                        if (StringUtils.isNotNull(successBean)){
                            UserInfoBean.DataDTO dataDTO = successBean.getData();
                            if (StringUtils.isNotNull(dataDTO)){
                                RxSPTool.putString(mActivitySelf, "token", dataDTO.getBearer());
                                RxSPTool.putInt(mActivitySelf, "memberId", dataDTO.getId());
                                RxSPTool.putBoolean(mActivitySelf,HXYXConstant.FIRST_OPEN,true);
                                Log.d("bearer", "onSuccess: " + dataDTO.getBearer());
                                SharedPreferencesUtils.setParam(getApplicationContext(), SharedPreferencesUtils.isLogin, true);
                                goTo(MainActivity.class);
                                login.reset();
                                finish();
                            }
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, String error_msg) {
                        hideDialogLoading();
                        ToastUtils.show(error_msg);
                        login.netFaile("登录");
                        login.setSmartClickable(true);
                    }
                });
                break;
            case R.id.tv_forgot_password:
                /**忘记密码*/

                break;
            case R.id.tv_register:
                /**注册*/
                goTo(RegisterActivity.class);
                break;
            case R.id.tv_skip:
                /**跳过*/
                RxSPTool.putBoolean(mActivitySelf, HXYXConstant.FIRST_OPEN,true);
                hideSoftKeyBoard(mActivitySelf);
                goTo(MainActivity.class);
                finish();
                break;
            case R.id.rel_finish:
                hideSoftKeyBoard(mActivitySelf);
                if (StringUtils.equals(type,"403")){
                    Intent i = new Intent(RxTool.getContext(), MainActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(i);
                    finish();
                }else {
                    finish();
                }

                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(et_phone.getText().toString().trim()) && !TextUtils.isEmpty(et_password.getText().toString().trim())) {
            login.setSmartClickable(true);
        } else {
            login.setSmartClickable(false);
        }
    }
}
